package com.whfc.fse.queue;

import com.alibaba.fastjson.JSON;
import com.whfc.common.constant.QueueConst;
import com.whfc.common.exception.BizException;
import com.whfc.common.result.ResultEnum;
import com.whfc.common.spring.AppContextUtil;
import com.whfc.fse.dao.FseLiftMapper;
import com.whfc.fse.dao.FseLiftRecordMapper;
import com.whfc.fse.dto.FseLiftRecordDTO;
import com.whfc.fse.entity.FseLift;
import com.whfc.fse.entity.FseLiftRecord;
import com.whfc.fse.enums.FseLiftSide;
import com.whfc.fse.event.SyncLiftRecordEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author : qzexing
 * @version : 1.0
 * @date : 2020-07-17 18:04
 */
@Component
@RabbitListener(queuesToDeclare = {@Queue(name = QueueConst.FSE_LIFT_RECORD_DATA)}, concurrency = "1-2",containerFactory = "baseFactory")
public class FseLiftRecordDataQueueListener {

    private static final Logger logger = LoggerFactory.getLogger(FseLiftRecordDataQueueListener.class);

    @Autowired
    private FseLiftRecordMapper fseLiftRecordMapper;

    @Autowired
    private FseLiftMapper fseLiftMapper;

    @RabbitHandler
    public void handle(String msg) {
        try {
            logger.info("消息消费者处理升降机运行记录,msg:{}", msg);
            FseLiftRecordDTO liftRecordDTO = JSON.parseObject(msg, FseLiftRecordDTO.class);
            String sn = liftRecordDTO.getSn();
            String platform = liftRecordDTO.getPlatform();
            FseLift fseLift = fseLiftMapper.selectByPlatformAndSn(platform, sn);
            if (fseLift == null) {
                throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "该升降机不存在, sn:" + sn);
            }
            int liftSide = FseLiftSide.LEFT.getValue();
            if (sn.equals(fseLift.getRightSn())) {
                liftSide = FseLiftSide.RIGHT.getValue();
            }
            Integer liftId = fseLift.getId();
            FseLiftRecord fseLiftRecord = new FseLiftRecord();
            BeanUtils.copyProperties(liftRecordDTO, fseLiftRecord);
            fseLiftRecord.setLiftSide(liftSide);
            fseLiftRecord.setLiftId(liftId);
            fseLiftRecordMapper.insertSelective(fseLiftRecord);
            liftRecordDTO.setSn(sn);
            //推送吊装记录事件
            SyncLiftRecordEvent event = new SyncLiftRecordEvent(fseLift.getDeptId(), liftRecordDTO);
            AppContextUtil.context().publishEvent(event);
        } catch (Exception e) {
            logger.error("消息消费者处理升降机运行记录失败", e);
        }

    }
}
